package com.gszy.auth.security;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class AuthenticationFilter implements Filter {
    private final String LOGIN_PROCESS_URL = "/auth/login.do";

    private final String LOGIN_PAGE_URL = "/pages/login.jsp";

    private ExcludedUrlConfiguration excludedUrlConfiguration = ExcludedUrlConfiguration.getInstance();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

        //将不需要拦截的请求设置到ExcludedUrlConfiguration
        excludedUrlConfiguration.addExcludedUrl(LOGIN_PAGE_URL);
        excludedUrlConfiguration.addExcludedUrl(LOGIN_PROCESS_URL);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        /**
         * 1.获取请求的url地址
         * 2.判断本次请求是否需要拦截 如果不需要直接放行
         * 3.认证 从sesssion获取登录信息
         * 4.如果没有获取到 就跳转到登录页面
         * 5.如果有登录信息 将session中的用户信息放到SecurityContextHolder 并且将请求传递到下个Filter
         */

        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //url http://localhost:8080/xxx/xxx.do
        //uri /xxx/xxx.do
        // /webapp-name/xxx/xxx.do
        String requestURI = request.getRequestURI();

        // /xxx/xxx.do
        String realURI = requestURI.replaceAll(request.getContextPath(),"");

        try {
            if (excludedUrlConfiguration.isUrlExcluded(realURI)){
                filterChain.doFilter(servletRequest,servletResponse);
                return;
            }
            HttpSession session = request.getSession();
            UserDetails auth = (UserDetails) session.getAttribute("auth");
            if (auth == null){
                response.sendRedirect(request.getContextPath()+LOGIN_PAGE_URL);
            }else {

                SecurityContextHolder.getInstance().addUserDetails(auth);
                filterChain.doFilter(servletRequest,servletResponse);
            }

        }finally {
            SecurityContextHolder.getInstance().removeUserDetails();
        }

    }

    @Override
    public void destroy() {

    }
}
